package alijk.dataView.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import alijk.dataView.utils.DBConnection;

/**
 * 取garuda的数据
 * @time 2014年11月07日 下午5:28:03
 * @author CheWenliang
 */
@Controller
@Scope(value = "prototype")
@RequestMapping("/garudaView")
public class GarudaDataViewController {
	public static final Logger logger = LoggerFactory
			.getLogger(GarudaDataViewController.class);
	
	
	@RequestMapping("/tolist.do")
	public String tolist() {
		return "garudaView/dataView";
	}
	/**
	 * 取数据
	 * @param sql
	 * @param page
	 * @return
	 */

	@RequestMapping("/getData.do")
	@ResponseBody
	public Map<String,Object> getData(
			@RequestParam(value = "sql", required = false) String sql,
			@RequestParam(value = "page", required = false,defaultValue = "1") int page) {
		Map<String,Object> resultMap = new HashMap<String, Object>();
		DBConnection dbConn = DBConnection.getInstance();	
		Connection conn = dbConn.getConnection();
		if(page == 0){
			page = 1;
		}
		Statement stmt = null;
		ResultSet rs = null;
		List<Object> listall = new ArrayList<Object>();
		List<String> disNames = new ArrayList<String>();
		List<Object> datas = new ArrayList<Object>();
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			int colCount = rs.getMetaData().getColumnCount();
			//得到显示的名
			for (int i = 0; i < colCount-1; i++) {
				String coluName = rs.getMetaData().getColumnLabel(i+1);
				disNames.add(coluName);
			}
			listall.add(disNames);
			//得到数据
			while (rs.next()) {
				LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<String, Object>();
				for(int i=0;i<disNames.size();i++){
					Object value = rs.getObject(disNames.get(i));
					linkedHashMap.put(disNames.get(i), value);
				}
				datas.add(linkedHashMap);
			}
			logger.info("本地执行的SQL："+sql);
			
			//根据page拿 到相应的20条记录
			resultMap.put("total", datas.size());
			datas = getCurrentData(datas,Long.valueOf(datas.size()),page,20);
			resultMap.put("success", true);
			resultMap.put("names", disNames);
			resultMap.put("datas", datas);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			resultMap.put("success", false);
			resultMap.put("message", e.getMessage().replaceAll("\\n", "<br/>"));
			return resultMap;
		} finally{
			try {
				if(rs !=null ){
					rs.close();
				}
				if(stmt != null){
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return resultMap; 
	}
	/**
	 * 截取
	 * @param resultData
	 * @param dataCount
	 * @param page
	 * @param rows
	 * @return
	 */
	private List<Object> getCurrentData(List<Object> resultData,Long dataCount,int page,int rows){
		List<Object> currentList = new ArrayList<Object>();
		int currentPage = 1;
		Long pages = dataCount % rows == 0 ? dataCount / rows : dataCount / rows + 1;
		// 不足一页数据数量
		if(pages == 1L){
			currentPage = 1;
		}else{
			//如果page大于等于总页数
			if(page >= pages){
				currentPage = pages.intValue();//显示最后一页
			}else{
				currentPage = page;
			}
		}
		//判断初页数据数量等于0时，起始偏移量会出现-10现象
		if(currentPage==0)
		{
			currentPage=1;
		}
		// 起始偏移量
		int idx_start = ((currentPage - 1) * rows);
		
		// 结束偏移量
		int idx_end = currentPage * rows;
		if(idx_end > dataCount){
			idx_end = dataCount.intValue();
		}
		if(null !=resultData && resultData.size()>0){
			currentList = resultData.subList(idx_start, idx_end);
		}
		return currentList;
		
	}
}
